#include<stdio.h>
#include<pthread.h>
#include<unistd.h>

#define THREAD_COUNT 2

int g_bowl = 0;  //0没有面，1有面
pthread_mutex_t g_lock; //互斥锁
pthread_cond_t g_eat_cond; //条件变量
pthread_cond_t g_make_cond;

void* eat_thread(void* arg){
    while(1){
        pthread_mutex_lock(&g_lock);
        while(g_bowl == 0){
            printf("我是吃面人，碗里面没面我就不吃了\n");
            pthread_cond_wait(&g_eat_cond, &g_lock);
            //pthread_mutex_unlock(&g_lock);
            //continue;
        }
        printf("I am eat thread, eat %d\n", g_bowl--);
        //解锁
        pthread_mutex_unlock(&g_lock);
        //通知做面线程
        pthread_cond_signal(&g_make_cond);
       // usleep(1);
    }
}
void* make_thread(void* arg){
    while(1){
        pthread_mutex_lock(&g_lock);
        while(g_bowl == 1){
            printf("我是做面人，碗里面有面，我就不做了。。。\n");
            pthread_cond_wait(&g_make_cond, &g_lock);
            //pthread_mutex_unlock(&g_lock);
            //continue;
        }
        printf("I am make thread, make %d\n", g_bowl++);
        //解锁
        pthread_mutex_unlock(&g_lock);
        //通知吃面线程
        pthread_cond_signal(&g_eat_cond);
        //usleep(1);
    }
}
int main(){
    //初始化互斥锁
    pthread_mutex_init(&g_lock, NULL);
    //初始化条件变量
    pthread_cond_init(&g_eat_cond,  NULL);
    pthread_cond_init(&g_make_cond, NULL);

    pthread_t eat[THREAD_COUNT], make[THREAD_COUNT];
    //创建吃面和做面线程
    for(int i = 0; i < THREAD_COUNT; ++i){
        int ret = pthread_create(&eat[i], NULL, make_thread, NULL);
        if(ret < 0){
            perror("pthread_creat");
            return 0;
        }
        ret = pthread_create(&make[i], NULL, eat_thread, NULL);
        if(ret < 0){
            perror("pthread_creat");
            return 0;
        }
    }
    //主线程等待工作线程
    for(int i = 0; i < THREAD_COUNT; ++i){
        pthread_join(eat[i], NULL);
        pthread_join(make[i], NULL);
    }
    //销毁互斥锁
    pthread_mutex_destroy(&g_lock);
    //销毁条件变量
    pthread_cond_destroy(&g_eat_cond);
    pthread_cond_destroy(&g_make_cond);
    return 0;
}
